package com.mvc.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 拦截器链由  容器在初始化时建立，而不是动态建立
 */
public class HandlerExecutionChain {
	// 维护一个 拦截器数组
	private List<HandlerInterceptor> interceptorList = new ArrayList<>();
	
	private HandlerInterceptor[] interceptors;
	
	public HandlerInterceptor[] getInterceptors() {
		if (interceptors == null) {
			interceptors = interceptorList.toArray(new HandlerInterceptor[0]);
		}
		return interceptors;
	}
	
	public void clear() {
		interceptorList = new ArrayList<>();
		interceptors = null;
	}
	
	
	
	public void addInterceptor(HandlerInterceptor handlerInterceptor) {
		if (!interceptorList.contains(handlerInterceptor)) {
			interceptorList.add(handlerInterceptor);
		}
	}
	
	
	// 应用所有的预处理方法
	public boolean applyPreHandler(HttpServletRequest request, HttpServletResponse response) throws Exception {
		for (HandlerInterceptor interceptor : interceptorList) {
			if (!interceptor.preHandle(request, response)) {
				return false;
			}
		}
		return true;
	}
	
	// 应用所有的后处理方法
	public void applyPostHandler(HttpServletRequest request, HttpServletResponse response,Object result) throws Exception {
		HandlerInterceptor[] handlerInterceptors = getInterceptors();
		for (int i = handlerInterceptors.length - 1; i >= 0; i--) {
			handlerInterceptors[i].postHandle(request, response,result);   // result 有什么意义么，单纯的给 json转换用？
		}
	}
	
	// 应用所有的完成处理方法
	public void applyAfterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception {
		HandlerInterceptor[] handlerInterceptors = getInterceptors();
		for (int i = handlerInterceptors.length - 1; i >= 0; i--) {
			handlerInterceptors[i].afterCompletion(request, response, ex);
		}
	}
}
